package com.pine.dcts.core;

import com.alibaba.datax.common.constant.PluginType;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.core.util.container.CoreConstant;
import com.pine.dcts.entity.DatasourceInfo;
import com.pine.dcts.service.DatasourceService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author xiaoyuan
 * @create 2020/11/27 10:12
 **/

public abstract class AbstractPluginConfigHandler implements IPluginConfigHandler {
    protected static final String DATASOURCE_ID = "datasourceId";
    protected static final String USER_NAME = "username";
    protected static final String PASSWORD = "password";
    protected static final String JDBC_URL = "connection[0].jdbcUrl[0]";

    @Autowired
    protected DatasourceService datasourceService;

    @Override
    public void supplementConfig(PluginType pluginType, Configuration configuration) {
        Configuration pluginConfiguration;
        switch (pluginType) {
            case READER:
                pluginConfiguration = configuration.getConfiguration(CoreConstant.DATAX_JOB_CONTENT_READER_PARAMETER);
                supplementPluginConfig(pluginType, pluginConfiguration);
                configuration.set(CoreConstant.DATAX_JOB_CONTENT_READER_PARAMETER, pluginConfiguration);
                break;
            case WRITER:
                pluginConfiguration = configuration.getConfiguration(CoreConstant.DATAX_JOB_CONTENT_WRITER_PARAMETER);
                supplementPluginConfig(pluginType, pluginConfiguration);
                configuration.set(CoreConstant.DATAX_JOB_CONTENT_WRITER_PARAMETER, pluginConfiguration);
                break;
            case TRANSFORMER:
                break;
        }


    }

    @Override
    public void supplementPluginConfig(PluginType pluginType, Configuration configuration) {
        switch (pluginType) {
            case READER:
                Integer datasourceId = configuration.getInt(DATASOURCE_ID);
                if (datasourceId != null) {
                    DatasourceInfo datasourceInfo = this.datasourceService.getById(datasourceId);
                    if (datasourceInfo != null) {
                        configuration.set(USER_NAME, datasourceInfo.getUsername());
                        configuration.set(PASSWORD, datasourceInfo.getPassword());
                        configuration.set(JDBC_URL, datasourceInfo.getJdbcUrl());
                    }
                }
                break;
            case WRITER:
                break;
            case TRANSFORMER:
                break;
        }
        cleanPlguinConfig(configuration);
    }

    @Override
    public void supplementCoreConfig(Configuration configuration) {

    }

    @Override
    public void supplementJobConfig(Configuration configuration) {

    }

    public abstract void cleanPlguinConfig(Configuration configuration);


}
